package com.qf.gateway.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.qf.pojo.User;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

public class JWTUtil {

    /**
     * 用户信息生成Token
     *
     * @param user
     * @return
     */
    public static String createToken(User user) {
        //获取过期时间（一天后）
        Date expireDate = getExpireDate();
        String token = JWT.create()
                .withAudience(user.getId().toString())
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(user.getPassword()));
        return token;
    }

    private static Date getExpireDate() {
        LocalDate expireLocalDate = LocalDate.now().plusDays(1);
        Instant instant = expireLocalDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

    public static void main(String[] args) {
        User user=new User();
        user.setPassword("123456");
        user.setId(1l);
        user.setUserName("jerry");
        System.out.println(createToken(user));
    }
}
